<?php

namespace App\Console\Commands;

use App\Console\Base;
use App\Models\Agent;
use App\Models\Message;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class SendMessage extends Base
{

    const SEND_TYPE_USER = 1;//会员层级
    const SEND_TYPE_AGENT = 2;//代理层级
    const SEND_TYPE_CUSTOM = 3;//自定义
    const STATUS_SENDED = 1;//已发布
    const STATUS_SENDING = 3;//发布中
    const BATCH = 10000;
    const USER = 1;
    const AGENT = 2;
    const IS_EFFECT = 1;
    /**
     * 控制台命令 signature 的名称。
     *
     * @var string
     */
    protected $signature = self::PREFIX . 'sendmessage';

    /**
     * 控制台命令说明。
     *
     * @var string
     */
    protected $description = 'SendMessage';

    /**
     * 是否厅命令
     *
     * @var bool
     */
    protected $isHallCmd = true;

    /**
     * 执行控制台命令。
     *
     * @return mixed
     */
    public function handle()
    {
        $messageList = Message::where(['status' => static::STATUS_SENDING])->get();
        if ($messageList) {
            foreach ($messageList as $item) {
                //获取各自对应的厅ID
                $hallID = $item['hall_id'];
                //打印日志
                $this->info("send message: " . $item['title']);
                //发送消息
                $this->dispatch($item, $hallID);
                //修改消息状态
                $model = Message::find($item['id']);
                $model->update(['status' => static::STATUS_SENDED]);
            }
            $this->info("send message finished");
        } else {
            $this->info("send message list is  empty");
        }

    }

    private function dispatch($message, $hallID)
    {
        if ($message['send_type'] == self::SEND_TYPE_USER) {         //会员层级
            $key = 'level_id';
            $value = explode(',', trim($message['recipient']));
        } elseif ($message['send_type'] == self::SEND_TYPE_CUSTOM) {  //自定义名称
            $key = 'username';
            $value = explode(',', trim($message['recipient'], ','));
        }

        $userID = [];
        if ($message['send_type'] == self::SEND_TYPE_AGENT) {
            $userID = Agent::where(['status' => self::IS_EFFECT])->where(['hall_id' => $hallID])->select('id')->distinct()->get();
            if (empty($userID)) {
                $this->info("Agent list is empty");
            }
            $type = self::AGENT;
        } elseif ($message['send_type'] == self::SEND_TYPE_CUSTOM) {
            foreach ($value as $val) {
                $res = User::where([$key => $val])->first();
                if ($res) {
                    $userID[] = ['id' => $res['id']];
                } else {
                    $this->info("User list is empty");
                }
                $type = self::USER;
            }
        }

        $paramArr = [];
        if ($message['send_type'] == self::SEND_TYPE_USER) {
            $lastId = 0;
            for ($i = 0; ; $i++) {
                if ($i == 0) {
                    $re = User::whereIn($key, $value)->where(['hall_id' => $hallID])->orderBy('id')->limit(1000)->get()->toArray();
                } else {
                    $re = User::whereIn($key, $value)->where(['hall_id' => $hallID])->where('id', '>', $lastId)->orderBy('id')->limit(1000)->get()->toArray();
                }
                if (empty($re)) {
                    break;
                }
                if (!empty($re)) {
                    foreach ($re as $item) {
                        $paramArr[] = [
                            'type' => $message['type'],
                            'hall_id' => $hallID,
                            'recipient_id' => $item['id'],
                            'message_id' => $message['id']
                        ];
                        $lastId = $item['id'];
                    }
                    $this->messagePubAdd($paramArr);
                    unset($re, $paramArr);
                }
            }

        } else {
            if ($userID) {
                foreach ($userID as $item) {
                    $paramArr[] = [
                        'type' => $message['type'],
                        'hall_id' => $hallID,
                        'recipient_id' => $item['id'],
                        'message_id' => $message['id']
                    ];
                    if (count($paramArr) >= 1000) {
                        $this->messagePubAdd($paramArr);
                        unset($paramArr);
                    }
                }
                if (count($paramArr)) {
                    $this->messagePubAdd($paramArr);
                }
            }
        }
        return true;
    }

    private function messagePubAdd($paramArr)
    {
        DB::table('message_record')->insert($paramArr);
    }
}
